import es
import random

from wcs.libs.items import items
from wcs.libs.players import players

itemName = "Mole"
item = items.addItem(itemName)
item.setGroup("special")
item.setCost(10000)
item.setDescription("Teleport to the enemy base and look like one of them")
item.setMaxCount(1)
        
freezeTime = es.ServerVar("mp_freezetime")
        
def wcs_item_bought(event_var):
    """
    Executed when an item is brought. If the item brought was in deed a mole,
    then notify the user that next spawn will entail their mole. Also assign
    their inbuilt dictionary attribute to hold this information.
    """
    if event_var['item'] == itemName:
        userid = event_var["userid"]
        player = players[userid]
        text = "#greenMole #default- #lightgreenYou will be a mole next round"
        es.tell(userid, "#multi", text)
        player['mole'] = True
        
def player_spawn(event_var):
    """
    Executed when a player spawns. If they previously brought a mole item, then
    delay by the given freeze time + 5 seconds, and set up the mole function.
    """
    userid = event_var["userid"]
    player = players[userid]
    if "mole" in player and player["mole"] is True:
        del player["mole"]
        time = float(freezeTime) + 5
        text = "#greenMole #default- #lightgreenYou will become a mole in %s "
        es.tell(userid, "#multi", (text + "seconds") % time)
        prop = {
            "3": "info_player_terrorist",
            "2": "info_player_counterterrorist"
        }[event_var["es_userteam"]]
        player.delayed(time, executeMole, (userid, prop))
        
def executeMole(userid, entityList):
    """
    This function will change a player's model to the opposition, and set their
    position at one of the spawn locations within the enemy team.
    
    @param int userid The ID of the user this effects
    @param str entityList A string containing the entity classname of the spawn
                          points, info_player_(counter)terrorist
    """
    team = es.getplayerteam(userid)
    if team == 2:
        model = random.choice(('ct_gign','ct_gsg9','ct_sas','ct_urban'))
    elif team == 3:
        model = random.choice(('t_arctic','t_phoenix','t_guerilla','t_leet'))
    else:
        return
    players[userid].model("player/%s" % model)
    entity = random.choice(es.createentitylist(entityList))
    origin = es.getindexprop(entity, "CBaseEntity.m_vecOrigin")
    x, y, z = map(float, origin.split(","))
    es.setpos(userid, x, y, z)